/*
 * The MIT License
 *
 * Copyright 2012 http://generic-toolset.googlecode.com.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package org.rlpw.swing;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

abstract class StateModel<T> implements SelectionMode {

    private View<T> view;
    private Set<T> states = new HashSet<>();
    private int mode = SelectModel.MULTIPLE;
    private boolean removeStates;

    StateModel(View<T> view, boolean removeStates) {
        this.view = view;
        this.removeStates = removeStates;
    }

    boolean getState(int index) {
        rangeCheck(index);
        return getState(getView().getVisibleItems().get(index));
    }

    boolean getState(T element) {
        if (removeStates && getView() != null) {
            try {
                List<T> visibleItems = getView().getVisibleItems();
                List<T> items = new LinkedList<>();

                for (T item : states) {
                    if (!visibleItems.contains(item)) {
                        items.add(item);
                    }
                }
                states.removeAll(items);
            } catch (Exception excep) {
            }
        }
        return states.contains(element);
    }

    int size() {
        return states.size();
    }

    void setState(int index, boolean state) {
        rangeCheck(index);
        setState(getView().getVisibleItems().get(index), state);
    }

    void setState(T element, boolean state) {

        if (getMode() == SelectionMode.SINGLE && states.contains(element)) {
            return;
        }

        if (state) {
            states.add(element);
            if (getMode() == SelectionMode.SINGLE || (getMode() == SelectionMode.INTERVAL && !isInterval())) {
                states.clear();
                states.add(element);
            }
        } else {
            states.remove(element);
            if (getMode() == SelectionMode.INTERVAL && !isInterval()) {
                states.clear();
            }
        }

        getView().updateView();
    }

    void setAllState(boolean state) {
        if (state && getMode() != SelectionMode.SINGLE) {
            states = new HashSet(view.getVisibleItems());
        } else {
            states.clear();
        }
        getView().updateView();
    }

    List<T> getStates() {
        return new ArrayList(states);
    }

    @Override
    public void setMode(int mode) {
        this.mode = mode;
        states.clear();
        getView().updateView();
    }

    @Override
    public int getMode() {
        return mode;
    }

    private void rangeCheck(int index) {
        if (index >= view.getVisibleItems().size()) {
            throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + view.getVisibleItems().size());
        }
    }

    private boolean isInterval() {
        List<Integer> ls = new ArrayList<>();
        for (T e : states) {
            ls.add(getView().getVisibleItems().indexOf(e));
        }

        Collections.sort(ls);
        int lastIndex = -1;
        for (int index : ls) {
            if (lastIndex == -1 || lastIndex + 1 == index) {
                lastIndex = index;
            } else {
                return false;
            }
        }
        return true;
    }

    View<T> getView() {
        return view;
    }
}
